<template>
  <div class="model-designer-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">数据模型设计器</span>
          <div class="header-actions">
            <el-button @click="showAIDialog = true" type="primary">
              <el-icon><MagicStick /></el-icon>
              AI生成
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新建模型
            </el-button>
          </div>
        </div>
      </template>

      <!-- 模型列表 -->
      <el-table :data="models" border>
        <el-table-column prop="name" label="模型名称" width="200" />
        <el-table-column prop="tableName" label="表名" width="200" />
        <el-table-column prop="fields" label="字段数" width="100">
          <template #default="{ row }">
            {{ row.fields.length }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleViewSQL(row)">查看SQL</el-button>
            <el-button link type="success" @click="handleGenerate(row)">生成代码</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑模型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模型名称">
              <el-input v-model="form.name" placeholder="如：用户" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表名">
              <el-input v-model="form.tableName" placeholder="如：sys_user" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="2" />
        </el-form-item>

        <el-divider content-position="left">字段定义</el-divider>

        <el-button type="primary" size="small" @click="handleAddField" style="margin-bottom: 10px">
          <el-icon><Plus /></el-icon>
          添加字段
        </el-button>

        <el-table :data="form.fields" border size="small">
          <el-table-column label="字段名" width="150">
            <template #default="{ row }">
              <el-input v-model="row.name" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="字段类型" width="120">
            <template #default="{ row }">
              <el-select v-model="row.type" size="small">
                <el-option label="字符串" value="string" />
                <el-option label="整数" value="int" />
                <el-option label="浮点数" value="float" />
                <el-option label="布尔" value="boolean" />
                <el-option label="日期" value="date" />
                <el-option label="时间" value="datetime" />
                <el-option label="文本" value="text" />
                <el-option label="JSON" value="json" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="长度" width="80">
            <template #default="{ row }">
              <el-input v-model.number="row.length" size="small" v-if="['string', 'text'].includes(row.type)" />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="默认值" width="100">
            <template #default="{ row }">
              <el-input v-model="row.defaultValue" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="注释" width="150">
            <template #default="{ row }">
              <el-input v-model="row.comment" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="必填" width="60" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.required" />
            </template>
          </el-table-column>
          <el-table-column label="唯一" width="60" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.unique" />
            </template>
          </el-table-column>
          <el-table-column label="索引" width="60" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.index" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button link type="danger" size="small" @click="handleRemoveField($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- AI生成对话框 -->
    <el-dialog v-model="showAIDialog" title="AI生成数据模型" width="700px">
      <el-alert
        title="描述你需要的数据模型，AI会自动生成字段结构"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-input
        v-model="aiInput"
        type="textarea"
        :rows="5"
        placeholder="例如：创建一个商品管理模型，包含商品名称、编码、价格、库存、分类、品牌、状态等字段"
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          <el-icon><MagicStick /></el-icon>
          生成模型
        </el-button>
      </template>
    </el-dialog>

    <!-- SQL预览对话框 -->
    <el-dialog v-model="showSQLDialog" title="SQL预览" width="800px">
      <pre class="sql-preview">{{ generatedSQL }}</pre>
      <template #footer>
        <el-button @click="handleCopySQL">
          <el-icon><DocumentCopy /></el-icon>
          复制SQL
        </el-button>
        <el-button type="primary" @click="showSQLDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MagicStick, Plus, DocumentCopy } from '@element-plus/icons-vue'

const dialogVisible = ref(false)
const dialogTitle = ref('新建模型')
const showAIDialog = ref(false)
const showSQLDialog = ref(false)
const aiInput = ref('')
const aiGenerating = ref(false)
const generatedSQL = ref('')

const form = reactive({
  name: '',
  tableName: '',
  description: '',
  fields: []
})

const models = ref([
  {
    id: 1,
    name: '用户',
    tableName: 'sys_user',
    description: '系统用户表',
    createTime: '2025-01-10 10:00:00',
    fields: [
      { name: 'id', type: 'int', required: true, unique: true, comment: '主键ID' },
      { name: 'username', type: 'string', length: 50, required: true, unique: true, comment: '用户名' },
      { name: 'password', type: 'string', length: 100, required: true, comment: '密码' },
      { name: 'email', type: 'string', length: 100, comment: '邮箱' },
      { name: 'phone', type: 'string', length: 20, comment: '手机号' },
      { name: 'status', type: 'int', defaultValue: '1', required: true, comment: '状态' }
    ]
  },
  {
    id: 2,
    name: '商品',
    tableName: 'product',
    description: '商品信息表',
    createTime: '2025-01-12 14:30:00',
    fields: [
      { name: 'id', type: 'int', required: true, unique: true, comment: '主键ID' },
      { name: 'name', type: 'string', length: 200, required: true, comment: '商品名称' },
      { name: 'code', type: 'string', length: 50, required: true, unique: true, comment: '商品编码' },
      { name: 'price', type: 'float', required: true, comment: '价格' },
      { name: 'stock', type: 'int', defaultValue: '0', comment: '库存' },
      { name: 'category_id', type: 'int', index: true, comment: '分类ID' }
    ]
  }
])

const handleAdd = () => {
  dialogTitle.value = '新建模型'
  Object.assign(form, {
    name: '',
    tableName: '',
    description: '',
    fields: [
      { name: 'id', type: 'int', required: true, unique: true, comment: '主键ID' },
      { name: 'create_time', type: 'datetime', required: true, comment: '创建时间' },
      { name: 'update_time', type: 'datetime', comment: '更新时间' }
    ]
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑模型'
  Object.assign(form, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

const handleAddField = () => {
  form.fields.push({
    name: '',
    type: 'string',
    length: 50,
    defaultValue: '',
    comment: '',
    required: false,
    unique: false,
    index: false
  })
}

const handleRemoveField = (index) => {
  form.fields.splice(index, 1)
}

const handleSubmit = () => {
  if (!form.name || !form.tableName) {
    ElMessage.warning('请填写模型名称和表名')
    return
  }
  
  console.log('保存模型:', form)
  ElMessage.success('保存成功')
  dialogVisible.value = false
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除模型 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const handleViewSQL = (row) => {
  generatedSQL.value = generateSQL(row)
  showSQLDialog.value = true
}

const generateSQL = (model) => {
  const fields = model.fields.map(f => {
    let sql = `  \`${f.name}\` `
    
    switch (f.type) {
      case 'string':
        sql += `VARCHAR(${f.length || 50})`
        break
      case 'int':
        sql += 'INT'
        break
      case 'float':
        sql += 'DECIMAL(10,2)'
        break
      case 'boolean':
        sql += 'TINYINT(1)'
        break
      case 'date':
        sql += 'DATE'
        break
      case 'datetime':
        sql += 'DATETIME'
        break
      case 'text':
        sql += 'TEXT'
        break
      case 'json':
        sql += 'JSON'
        break
    }
    
    if (f.required) sql += ' NOT NULL'
    if (f.defaultValue) sql += ` DEFAULT '${f.defaultValue}'`
    if (f.comment) sql += ` COMMENT '${f.comment}'`
    
    return sql
  }).join(',\n')

  const indexes = model.fields
    .filter(f => f.unique || f.index)
    .map(f => {
      if (f.unique) return `  UNIQUE KEY \`uk_${f.name}\` (\`${f.name}\`)`
      if (f.index) return `  KEY \`idx_${f.name}\` (\`${f.name}\`)`
    })
    .join(',\n')

  return `CREATE TABLE \`${model.tableName}\` (
${fields},
  PRIMARY KEY (\`id\`)${indexes ? ',\n' + indexes : ''}
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='${model.description}';`
}

const handleCopySQL = () => {
  navigator.clipboard.writeText(generatedSQL.value)
  ElMessage.success('SQL已复制到剪贴板')
}

const handleGenerate = (row) => {
  ElMessage.info('代码生成功能开发中...')
}

const handleAIGenerate = () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }

  aiGenerating.value = true

  setTimeout(() => {
    // 模拟AI生成
    Object.assign(form, {
      name: '商品',
      tableName: 'product',
      description: 'AI生成的商品管理模型',
      fields: [
        { name: 'id', type: 'int', required: true, unique: true, comment: '主键ID' },
        { name: 'name', type: 'string', length: 200, required: true, comment: '商品名称' },
        { name: 'code', type: 'string', length: 50, required: true, unique: true, index: true, comment: '商品编码' },
        { name: 'price', type: 'float', required: true, comment: '价格' },
        { name: 'stock', type: 'int', defaultValue: '0', required: true, comment: '库存数量' },
        { name: 'category_id', type: 'int', required: true, index: true, comment: '分类ID' },
        { name: 'brand_id', type: 'int', index: true, comment: '品牌ID' },
        { name: 'status', type: 'int', defaultValue: '1', required: true, comment: '状态：1启用 0停用' },
        { name: 'create_time', type: 'datetime', required: true, comment: '创建时间' },
        { name: 'update_time', type: 'datetime', comment: '更新时间' }
      ]
    })
    
    ElMessage.success('模型生成成功')
    aiGenerating.value = false
    showAIDialog.value = false
    dialogVisible.value = true
  }, 2000)
}
</script>

<style scoped>
.model-designer-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.sql-preview {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
}
</style>

